package com.starbaba.module.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSONObject;
import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.module.model.ModelVO;
import com.starbaba.module.model.ModuleVO;
import com.starbaba.module.model.Universal_model;
import com.starbaba.module.model.Universal_module;
import com.starbaba.module.service.IModelService;
import com.starbaba.tools.sequence.Sequence;

@SuppressWarnings({"rawtypes","unchecked","deprecation"})
public class ModelAction extends BaseAction implements ModelDriven {

    private static final long serialVersionUID = 1L;

    @SuppressWarnings("unused")
    private ModelVO model;

	private IModelService service;

	@Autowired
	@Qualifier("modelServiceImpl")
	public void setService(IModelService service) {
		this.service = service;
	}

	private ArrayList<ControlLogCategory> logCategorysArrayList;

	@Override
	public ModelVO getModel() {

		return null;
	}

    public void moduleList() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		List list = service.getDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			LogService.error(e);
		}
	}

	public String detail() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String id = (String) paramsMap.get("id");
			if (id == null) {
				return ActionSupport.ERROR;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return ActionSupport.ERROR;
		}
		return ActionSupport.SUCCESS;
	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public String saveModel() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		// service.saveModule(paramsMap);
		String name = (String) paramsMap.get("name");
		String demo = (String) paramsMap.get("demo");
		String type = (String) paramsMap.get("type");

		ModelVO model = new ModelVO();
		model.setName(name);
		model.setDemo(demo);
		model.setCtime(new Date());
		if(!StringUtils.isEmpty(type)){
			model.setType(Integer.parseInt(type));
		}
		model.setId(Sequence.getSequence());
		try {
			// dao.add(model);
			getService().doCreate(ModelVO.class, model);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "add_success";

	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void saveModule() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		// service.saveModule(paramsMap);
		String model_id = (String) paramsMap.get("model_id");
		if (model_id != null && !model_id.equals("")) {

			service.saveModule(paramsMap, model_id);

			JSONObject obj = new JSONObject();
			obj.put("success", "true");
			try {
				this.sendJsonMessage(obj.toJSONString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void getModuleList() throws IOException {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String model_id = (String) paramsMap.get("model_id");

		List list = getService().doFindByHQL("from ModuleVO t where t.model_id=? ", Long.parseLong(model_id));
		PageResponse pageResponse = new PageResponse();
		pageResponse.setAaData(list);
		sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));

	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void copyModel() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String model_id = (String) paramsMap.get("model_id");
		service.copyModel(model_id);
		JSONObject obj = new JSONObject();
		obj.put("success", "true");
		try {
			sendJsonMessage(JsonUtils.toJson(obj, null, true, null, false));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 修改备注
	 */
	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void updateBgComments() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String backup = (String) paramsMap.get("backup");
		String name = (String) paramsMap.get("name");
		try {
			if (name != null && name != "") {
				this.getService().executeHQLUpdate(" update ModelVO vo set vo.name = ? where id = ? ", new Object[] { name, Long.valueOf(id) });
			} else {
				this.getService().executeHQLUpdate(" update ModelVO vo set vo.demo = ? where id = ? ", new Object[] { backup, Long.valueOf(id) });
			}

			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "备注成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@LogAble(operate = LogAble.OPERATE_DEL)
	public void delModel() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String operation = (String) paramsMap.get("operation");

		if (operation.equals("del")) {
			service.delModel(id);
		} else if (operation.equals("online")) {
			service.onlineModel(id);
		}

		JsonObject result = new JsonObject();
		ResultJson resultJs = new ResultJson();
		resultJs.msg = "操作成功";
		result.add("result", resultJs.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void modelView() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		ModuleVO moduleVO = (ModuleVO) this.getService().findUniqueByHQL(" from ModuleVO vo where id = ? ", new Object[] { Long.valueOf(id) });

		try {
			sendJsonMessage(JsonUtils.toJson(moduleVO));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public String getActionId() {
		// 1000001601
		// 1000001301 test
		return "1000001601";
	}

	@Override
	public ArrayList<ControlLogCategory> getProduct() {
		return logCategorysArrayList;
	}

    public void copytotest() {
		BaseDao dao = new BaseDao(Constant.POOL_LIFE);// 正式数据库
		BaseDao testdao = new BaseDao(Constant.POOL_PUSH_RW);// 测试数据库
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");

		try {
			if (!StringUtils.isEmpty(id)) {
				String universal_modelSql = "select * from universal_model where  id =? or parent_id =?";
				List<Universal_model> listModel = dao.list(universal_modelSql, Universal_model.class, Long.parseLong(id), Long.parseLong(id));
				boolean flag = checkTestdb(Long.parseLong(id), testdao);
				if (!flag) {
					String universal_moduleSql = "select * from universal_module where model_id = ?";
					for (Universal_model model : listModel) {
						List<Universal_module> moduleList = dao.list(universal_moduleSql, Universal_module.class, model.getId());
						for (Universal_module module : moduleList) {
							testdao.add(module);
						}
						testdao.add(model);
					}
				}
			}
			responseSuccess();
		} catch (Exception e) {
			responseError(e);
		}

	}

	public boolean checkTestdb(Long id, BaseDao testdao) {
		String testModelSql = "select count(1) from universal_model where id =? or parent_id =?";
		int i = 0;
		try {
			i = testdao.getInt(testModelSql, id, id);
		} catch (AppException e) {
			LogService.error(e);
		}
		if (i > 0) {
			return true;
		} else {
			return false;
		}

	}

	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description <p>
	 *              返回错误信息
	 *              </p>
	 *              　　　　　
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

}
